console.log('Background script 启动');

// 处理跨域请求
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log('Background收到消息:', request);
  
  if (request.type === 'fetchUrl') {
    // 使用Promise包装fetch请求
    (async () => {
      try {
        const response = await fetch(request.url);
        const data = await response.text();
        console.log('Fetch成功:', request.url);
        sendResponse({ success: true, data: data });
      } catch (error) {
        console.error('Fetch失败:', error);
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true; // 保持消息通道打开
  }

  if (request.type === 'downloadImage') {
    console.log('开始下载图片:', request.url);
    
    // 使用Promise包装下载过程
    (async () => {
      try {
        const response = await fetch(request.url, {
          credentials: 'omit',
          headers: {
            ...request.headers,
            'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'
          }
        });
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        // 直接使用下载API
        chrome.downloads.download({
          url: request.url,
          filename: request.filename,
          saveAs: false,
          conflictAction: 'uniquify'
        }, (downloadId) => {
          if (chrome.runtime.lastError) {
            console.error('下载失败:', chrome.runtime.lastError);
            sendResponse({ success: false, error: chrome.runtime.lastError });
          } else {
            console.log('下载成功:', downloadId);
            sendResponse({ success: true, downloadId: downloadId });
          }
        });
      } catch (error) {
        console.error('下载失败:', error);
        sendResponse({ success: false, error: error.message });
      }
    })();
    return true; // 保持消息通道打开
  }
  
  // 转发消息给content script
  if (request.type === 'startCrawl' || request.action === 'togglePanel') {
    console.log('转发消息到content script:', request);
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (tabs[0]) {
        chrome.tabs.sendMessage(tabs[0].id, request)
          .then(response => sendResponse(response))
          .catch(error => {
            console.error('发送消息失败:', error);
            sendResponse({ success: false, error: error.message });
          });
      }
    });
    return true; // 保持消息通道打开
  }
});

// 处理扩展图标点击事件
chrome.action.onClicked.addListener((tab) => {
  console.log('扩展图标被点击');
  
  // 先注入content script
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    files: ['content.js']
  }).then(() => {
    // content script加载完成后再发送消息
    setTimeout(() => {
      chrome.tabs.sendMessage(tab.id, { action: 'togglePanel' }, (response) => {
        if (chrome.runtime.lastError) {
          console.log('Panel切换消息发送失败，可能是正常的:', chrome.runtime.lastError);
        } else {
          console.log('Panel切换成功');
        }
      });
    }, 100); // 给content script一点时间初始化
  }).catch(err => {
    console.error('注入content script失败:', err);
  });
}); 